﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

namespace Systems.SaveSystem
{
    public class GuidSaveManager
    {
        private string savePath => Application.persistentDataPath + "/scene_data.dat";

        // 可保存对象 每次游戏开始时guid对应的object会变 所以要每次更新
        public Dictionary<string, GuidSaveCompAbs> sceneObjects = new Dictionary<string, GuidSaveCompAbs>();

        public Dictionary<string, Dictionary<string, object>> sceneData =
            new Dictionary<string, Dictionary<string, object>>();

        // 静态初始化器，由CLR保证线程安全
        private static readonly GuidSaveManager instance = new GuidSaveManager();
        public static GuidSaveManager Instance => instance;

        private GuidSaveManager()
        {
            if (!File.Exists(savePath)) return;
            using (FileStream stream = new FileStream(savePath, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                sceneData = (Dictionary<string, Dictionary<string, object>>)formatter.Deserialize(stream);
            }
        }

        // 注册可保存对象
        public void RegisterSaveable(GuidSaveCompAbs obj)
        {
            sceneObjects[obj.guid] = obj;
            if (!sceneData.ContainsKey(obj.guid))
            {
                sceneData[obj.guid] = null;
            }
        }

        // 保存场景数据
        public void SaveScene()
        {
            // 保存的 数据
            foreach (var obj in sceneObjects.Values)
            {
                if (sceneObjects[obj.guid] == null)
                {
                    Debug.Log("对象已被销毁");
                    Dictionary<string, object> data = new Dictionary<string, object>();
                    data.Add("Dead", true);
                    sceneData[obj.guid] = data;
                }
                else
                {
                    sceneData[obj.guid] = obj.SaveData();
                }
            }

            using (FileStream stream = new FileStream(savePath, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, sceneData);
            }
        }
    }
}